# HTTP basic auth case
# 实例1 ：httpbin.org 提供了 Auth demo
# 使用前先登陆该网站，进行设置后可获得相应示例的 request url，复制该 url 到本程序作为初始访问的 url。

import urllib.request
import urllib.error
import urllib.parse

if __name__ == '__main__':
    # 我设定的用户名为 wxhh ，密码为 123456

    headers = {
        'Accept': 'text/html,application/json,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    }

    username = 'wxhh'
    password = '123456'

    url = 'http://www.httpbin.org/basic-auth/wxhh/123456'
    # 若我们将 username 写错，如username = 'wxhh1'
    # 则运行结果为：HTTP Error 401: UNAUTHORIZED

    request = urllib.request.Request(url, headers=headers)

    # Create a password manager
    passmgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()

    # Because we have put None at the start
    # it will always use this username / password combination for urls
    # for which the url is a super-url
    passmgr.add_password(None, url, username, password)

    # create the AuthHandler
    authhandler = urllib.request.HTTPBasicAuthHandler(passmgr)

    opener = urllib.request.build_opener(authhandler)

    try:
        with opener.open(request) as response:
            print(response.status)
            print(response.read().decode('utf-8'))
    except urllib.error.URLError as e:
        print(e)
    except urllib.error.HTTPError as e:
        print(e)
        print(e.headers)
    except:
        print('Unknown error')